package com.reebake.ideal.message.websocket.config;

import com.reebake.ideal.message.websocket.core.WebSocketChannelInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebsocketMessageBrokerConfig implements WebSocketMessageBrokerConfigurer{
	public final static String BROKER_QUEUE = "/queue";
	public final static String BROKER_TOPIC = "/topic";
	public final static String PREFIX_APP = "/app";
	public final static String PREFIX_USER = "/user";
	
    @Autowired
    private WebSocketChannelInterceptor webSocketChannelInterceptor;
 
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket-endpoint").setAllowedOriginPatterns("*")
                .withSockJS();
    }
 
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 客户端发送消息的请求前缀
        registry.setApplicationDestinationPrefixes(PREFIX_APP);

        // 客户端订阅消息的请求前缀，topic一般用于广播推送，queue用于点对点推送
        registry.enableSimpleBroker(BROKER_TOPIC, BROKER_QUEUE);

        // 服务端通知客户端的前缀，可以不设置，默认为user
        registry.setUserDestinationPrefix(PREFIX_USER);
    }
 
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(webSocketChannelInterceptor);
    }
 
}
